<?php
class Ms_namasekolah extends CI_Controller {

	function __construct()
	{
		parent::__construct();	
		$this->load->helper('flexigrid');
		$this->load->library('flexigrid');
		$this->load->library('form_validation');
		$this->load->model('master_model');
		$this->load->helper(array('form', 'url'));
		$this->load->library('upload');
	}
	
	function index()
	{
		//ver lib
		
		/*
		 * 0 - display name
		 * 1 - width
		 * 2 - sortable
		 * 3 - align
		 * 4 - searchable (2 -> yes and default, 1 -> yes, 0 -> no.)
		 */
		$colModel['no'] = array('No',40,TRUE,'center',0);
		$colModel['NAMA_SEKOLAH'] = array('Nama Instansi',200,TRUE,'center',1);
		$colModel['ALAMAT_SEKOLAH_1'] = array('Alamat Sekolah',250,TRUE,'center',1);
		$colModel['NO_TELEPON_1'] = array('Telp',100,TRUE,'center',1);
		$colModel['WEBSITE'] = array('Website',150,TRUE,'center',1);
		$colModel['email'] = array('Email',150,TRUE,'center',1);
		$colModel['ISAKTIF'] = array('Is Aktif',100,TRUE,'center',1);
		$colModel['ubah'] = array('Edit',50,FALSE,'center',0);
		
		/*
		 * Aditional Parameters
		 */
		$gridParams = array(
		'width' => 'auto',
		'height' => '335',
		'rp' => 15,
		'rpOptions' => '[10,15,20,25,40]',
		'pagestat' => 'Displaying: {from} to {to} of {total} items.',
		'blockOpacity' => 0.5,
		'title' => 'Daftar Instansi'
		);
		
		/*
		 * 0 - display name
		 * 1 - bclass
		 * 2 - onpress
		 */
		if($this->session->userdata('roleid')=='0'){
			$buttons[] = array('Add','add','org_js');
		$buttons[] = array('Delete','delete','org_js');
		$buttons[] = array('separator');
		}
		$buttons[] = array('Select All','add','org_js');
		$buttons[] = array('Deselect All','delete','org_js');
		$buttons[] = array('separator');
		
		//Build js
		//View helpers/flexigrid_helper.php for more information about the params on this function
		$grid_js = build_grid_js('flex1',site_url("/ms_namasekolah/listsekolah_grid/"),$colModel,'no','asc',$gridParams,$buttons);
		
		$data['title'] = "Contoh Flexigrid";
		$data['info'] = "Flexigrid";
		$data['js_grid'] = $grid_js;
		$data['version'] = "0.36";
		$data['download_file'] = "Flexigrid_CI_v0.36.rar";
		
		$data['added_js'] = 
			"<script type='text/javascript'>
			function org_js(com,grid)
			{
				if (com=='Select All')
				{
					$('.bDiv tbody tr',grid).addClass('trSelected');
				}
				
				if (com=='Deselect All')
				{
					$('.bDiv tbody tr',grid).removeClass('trSelected');
				}
				
				if (com=='Add')
				{
					location.href='".base_url()."index.php/ms_namasekolah/input_namasekolah/'; 
				}
				
				if (com=='Delete')
				{
				   if($('.trSelected',grid).length>0){
					   if(confirm('Anda yakin ingin menghapus ' + $('.trSelected',grid).length + ' buah data?')){
							var items = $('.trSelected',grid);
							var itemlist ='';
							for(i=0;i<items.length;i++){
								itemlist+= items[i].id.substr(3)+',';
							}
							$.ajax({
							   type: 'POST',
							   url: '".site_url('/ms_namasekolah/delete_namasekolah')."',
							   data: 'items='+itemlist,
							   success: function(data){
								$('#flex1').flexReload();
								alert(data);
							   }
							});
						}
					} else {
						return false;
					} 
				}          
			} 
			</script>
			";
		
		/* $data['notification'] = "";
		if($this->session->userdata('notification')!=''){
			$data['notification'] = "
				<script>
					$(document).ready(function() {
						$.growlUI('Pesan :', '".$this->session->userdata('notification')."'); 
					});
				</script>
			";
		}//end if */	
		
		$data['content'] = $this->load->view('grid',$data,true);
		$this->load->view('main',$data);
		//$this->load->view('grid',$data);
		//$this->load->view('flexigrid',$data);
	}
	
	function listsekolah_grid()
	{
		//List of all fields that can be sortable. This is Optional.
		//This prevents that a user sorts by a column that we dont want him to access, or that doesnt exist, preventing errors.
		$valid_fields = array('ID_SEKOLAH','NAMA_SEKOLAH','ALAMAT_SEKOLAH_1','NO_TELEPON_1','WEBSITE','email','is aktif');
		
		$this->flexigrid->validate_post('ID_SEKOLAH','asc',$valid_fields);

		$records = $this->master_model->get_namasekolah();
		// var_dump($records);
		$this->output->set_header($this->config->item('json_header'));
		$no = 0;
		/*
		 * Json build WITH json_encode. If you do not have this function please read
		 * http://flexigrid.eyeviewdesign.com/index.php/flexigrid/example#s3 to know how to use the alternative
		 */
		foreach ($records['records']->result() as $row)
		{
			$record_items[] = array($row->ID_SEKOLAH,
			$no+1,
			'<div align="left">'.$row->NAMA_SEKOLAH .'</div>',
			'<div align="left">'.$row->ALAMAT_SEKOLAH_1 .'</div>',
			'<div align="left">'.$row->NO_TELEPON_1 .'</div>',
			'<div align="left">'.$row->WEBSITE .'</div>',
			'<div align="left">'.$row->email .'</div>',
			'<div align="center">'.($row->ISAKTIF == 1 ? "Ya" : "Tidak").'</div>',
			'<a href=\''.site_url().'/ms_namasekolah/edit_namasekolah/'.$row->ID_SEKOLAH.'/\'><img border=\'0\' src=\''.base_url().'images/main/28.png\'></a> '
			);
			$no++;
		}
		//Print please
		if(isset($record_items))
				$this->output->set_output($this->flexigrid->json_build($records['record_count'],$record_items));
			else
				$this->output->set_output('{"page":"1","total":"0","rows":[]}');
	}
	
	function cek_validasi() {	
			// Setting Rules
			$this->form_validation->set_rules('nama_sekolah', 'Nama Sekolah', 'required');
			$this->form_validation->set_rules('alamat_sekolah1', 'Alamat 1', 'required');
			$this->form_validation->set_rules('no_tlp1', 'No. Telp 1', 'required');
			
			// Setting Error Message
			$this->form_validation->set_message('required', 'Kolom %s harus diisi!!');
			
			// Setting Delimiter
			$this->form_validation->set_error_delimiters('<li class="error">', '</li>');
			return $this->form_validation->run();
	}
	
	function input_namasekolah()
    {
		if ($this->cek_validasi() == FALSE){
			$data['status'] = 'new';
			$data['dept'] = $this->master_model->combo_dept();
			$data['content'] = $this->load->view('form_namasekolah',$data,true);
			$this->load->view('main',$data);
		}
		else{
			$this->insert_namasekolah();
		}            
    }
	
	function insert_namasekolah(){
		$filenamees = explode('.',$_FILES['userfile']['name']);
		$filenamess = $filenamees[count($filenamees)-1];
		
		$data = array(
			'NAMA_SEKOLAH'			=> $this->input->post('nama_sekolah'),
			'ALAMAT_SEKOLAH_1'		=> $this->input->post('alamat_sekolah1'),
			'ALAMAT_SEKOLAH_2'		=> $this->input->post('alamat_sekolah2'),
			'NO_TELEPON_1'			=> $this->input->post('no_tlp1'),
			'NO_TELEPON_11'			=> $this->input->post('no_tlp11'),
			'NO_TELEPON_2'			=> $this->input->post('no_tlp2'),
			'NO_TELEPON_22'			=> $this->input->post('no_tlp22'),
			'FAX_1'					=> $this->input->post('fax1'),
			'FAX_2'					=> $this->input->post('fax2'),
			'WEBSITE'				=> $this->input->post('website'),
			'EMAIL'			 		=> $this->input->post('email'),
			'ISAKTIF'			 		=> $this->input->post('isaktif')
			
		);
		
		$ins_sekolah = $this->master_model->insert_namasekolah($data);
		$last_id = $this->master_model->get_last_id()->row()->ID_SEKOLAH;
		if($ins_sekolah == true){
			if($_FILES['userfile']['name']!= ''){
				$config['file_name'] = 'logo_instansi';
				$config['upload_path'] = './images/';
				$config['allowed_types'] = 'gif|jpg|png|jpeg';
				$config['max_size']	= '500';
				$this->upload->initialize($config);
				$this->load->library('upload', $config);
				
				if ( ! $this->upload->do_upload()){
					$data['err_msg'] = 'Maaf, file yang diupload tidak sesuai dengan format';
					$data['status'] = 'edit';
					$data['dept'] = $this->master_model->combo_dept();
					$data['rs_namasekolah'] = $this->master_model->get_namasekolahID($last_id);
					$data['content'] = $this->load->view('form_namasekolah',$data,true);
					$this->load->view('main',$data);
				}
				else {	
					$data2 = array();
					$data2['FOTO'] = 'logo_instansi.'.$filenamess;
					$this->master_model->update_namasekolah($data2,$last_id);
					
					$this->session->set_flashdata('suc_msg', 'Data berhasil disimpan.');
					redirect('ms_namasekolah');
					}				
			}else {	$this->session->set_flashdata('suc_msg', 'Data berhasil disimpan.');
					redirect('ms_namasekolah');
				}
		}
		// redirect('ms_namasekolah'); 
	}
	
	function edit_namasekolah($id_namasekolah)
    {
 		if ($this->cek_validasi() == FALSE){
				$data['status'] = 'edit';
				$data['dept'] = $this->master_model->combo_dept();
				$data['rs_namasekolah'] = $this->master_model->get_namasekolahID($id_namasekolah);
				$data['content'] = $this->load->view('form_namasekolah',$data,true);
				$this->load->view('main',$data);
			}
			else{
				$this->update_namasekolah($id_namasekolah);
			}            
    }
	
	function update_namasekolah($id_namasekolah){
		$filenamees = explode('.',$_FILES['userfile']['name']);
		$filenamess = $filenamees[count($filenamees)-1];
		
		$data = array(
			'ID_DEPARTMENT'			=> $this->input->post('department'),
			'NAMA_SEKOLAH'			=> $this->input->post('nama_sekolah'),
			'ALAMAT_SEKOLAH_1'		=> $this->input->post('alamat_sekolah1'),
			'ALAMAT_SEKOLAH_2'		=> $this->input->post('alamat_sekolah2'),
			'NO_TELEPON_1'			=> $this->input->post('no_tlp1'),
			'NO_TELEPON_11'			=> $this->input->post('no_tlp11'),
			'NO_TELEPON_2'			=> $this->input->post('no_tlp2'),
			'NO_TELEPON_2'			=> $this->input->post('no_tlp2'),
			'FAX_1'					=> $this->input->post('fax1'),
			'FAX_2'					=> $this->input->post('fax2'),
			'WEBSITE'				=> $this->input->post('website'),
			'EMAIL'			 		=> $this->input->post('email'),
			'ISAKTIF'			 		=> $this->input->post('isaktif')
		);
		// var_dump($_POST);exit;
		$this->master_model->update_namasekolah($data,$id_namasekolah);
		
		if($_FILES['userfile']['name']!= ''){
				$config['file_name'] = 'logo_instansi';
				$config['upload_path'] = './images/';
				$config['allowed_types'] = 'gif|jpg|png|jpeg';
				$config['max_size']	= '500';
				$this->upload->initialize($config);
				$this->load->library('upload', $config);
				
				//delete files //
				if($this->input->post('fileold')!= ''){
					unlink('images/'.$this->input->post('fileold'));
				}
				
				if ( ! $this->upload->do_upload()){
					$data['err_msg'] = 'Maaf, file yang diupload tidak sesuai dengan format';
					$data['status'] = 'edit';
					$data['dept'] = $this->master_model->combo_dept();
					$data['rs_namasekolah'] = $this->master_model->get_namasekolahID($id_namasekolah);
					$data['content'] = $this->load->view('form_namasekolah',$data,true);
					$this->load->view('main',$data);
				}
				else {	
						$data2 = array();
						$data2['FOTO'] = 'logo_instansi.'.$filenamess;
						$this->master_model->update_namasekolah($data2,$id_namasekolah);
						
						$this->session->set_flashdata('suc_msg', 'Data berhasil disimpan.');
						redirect('ms_namasekolah');
					}
			}
			else {	
				$this->session->set_flashdata('suc_msg', 'Data berhasil diupdate.');
				redirect('ms_namasekolah'); 
			}
		// redirect('ms_namasekolah'); 
	}
	
	function delete_namasekolah()
	{
		$ta_ids_post_array = explode(",",$this->input->post('items'));
		$msg = '';
		foreach($ta_ids_post_array as $index => $ta_id){
			if (isset($ta_id) && $ta_id != "") {
				$this->master_model->delete_namasekolah($ta_id);
						
			
			$msg .= "Data Sekolah berhasil dihapus.\n";
			}
		}
		$this->output->set_header($this->config->item('ajax_header'));
		$this->output->set_output($msg);
	}
	
}
?>
